package com.xianggu.demo;

public class BinarySearch {
    /**
     * 二分查找算法
     * @param arr
     * @param target
     * @return
     */
    public static int binarySearch(int[] arr, int target) {
        if (arr == null || arr.length == 0) {
            return -1;
        }

        int left = 0;
        int right = arr.length - 1;

        while( left <= right){
            int mid = left + (right - left) / 2;
            if( arr[mid] == target){
                return mid;
            } else if (arr[mid] < target) {
                left += mid;
            }else{
                right -= mid;
            }
        }
        
        return -1; // 未找到
    }

    public static void main(String[] args) {
        int[] sortedArray = {1, 3, 5, 7, 9, 11, 13};
        int target = 7;
        int result = binarySearch(sortedArray, target);
        System.out.println("目标值 " + target + " 的索引是: " + result);
    }
}